package demo.dcs.aspect;

import demo.dcs.MertricSendSchedule;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;

import java.lang.reflect.Field;


/**
 * @author mandy.hu
 */
public class RedisPoolAspectJ extends AbstractXdcsAspectJ {

    private static final Logger logger = LoggerFactory.getLogger(RedisPoolAspectJ.class);

    @Override
    public void beforeAspectJ(Object signature, Object instance, Object[] args) {
    }

    @Override
    public void afterAspectJ(Object result, Object signature, Object instance, Object[] args, Throwable throwable) {
        try {
            if (!mercurySwitch()) {
                return;
            }
            if (instance instanceof JedisPool && args.length == 6) {
                JedisPool pool = (JedisPool) instance;
                StringBuilder stringBuilder = new StringBuilder();
                if (args[1] instanceof String) {
                    stringBuilder.append(args[1]).append(":");
                }
                if (args[2] instanceof Integer) {
                    stringBuilder.append(args[2]);
                }
                if (args[5] != null && args[5] instanceof Integer) {
                    stringBuilder.append("-").append(args[5]);
                }
                String hostString = stringBuilder.toString();
                Field field = JedisPoolFieldsCache.getInstance().getInternalPoolFiled();
                try {
                    GenericObjectPool genericObjectPool = (GenericObjectPool) field.get(pool);
                    if (genericObjectPool != null) {
                        MertricSendSchedule.getMertricSendSchedule().addMertricListener(new GenericObjectPoolListener(genericObjectPool, hostString));
                    }
                } catch (Throwable e) {
                    logger.warn("RedisPoolAspectJ afterAspectJ get genericObjectPool error", e);
                }
            }
        } catch (Exception e) {
            logger.error("RedisPoolAspectJ afterAspectJ", e);
        }
    }
}
